<template>
  <div class="app-container">
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0px 0px 10px 0px;
      "
    >
      <el-button
        type="primary"
        plain
        icon="Plus"
        @click="handleAdd"
        v-hasPermi="['customerManagement:customerInfo:add']"
      >
        新增客户信息
      </el-button>

      <el-input
        v-model="queryParams.name"
        style="max-width: 200px; margin-left: 10px"
        placeholder="请输入客户名称"
        @change="handleQuery"
      >
        <template #append>
          <el-button :icon="Search" />
        </template>
      </el-input>
    </div>

    <el-table v-loading="loading" :data="dataSource">
      <el-table-column align="center" label="名称" prop="name" />
      <el-table-column align="center" label="手机号码" prop="phone" />
      <el-table-column align="center" label="客户职位" prop="position" />
      <el-table-column align="center" label="客户地址" prop="address" />
      <el-table-column align="center" label="详细地址" prop="addressDetail" />

      <el-table-column align="center" label="状态" width="180">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">{{
            scope.row.status == 1 ? "正常" : "不再合作"
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['customerManagement:customerInfo:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['customerManagement:customerInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户头像" prop="avatar">
          <image-upload v-model:modelValue="form.avatar" :limit="1" />
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="客户职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入客户职位" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="经纬度" prop="addressDetail">
          <div style="display: flex">
            <el-input
              v-model="form.addressDetail"
              placeholder="经纬度 例如：104.061382,30.569197"
              style="width: 400px"
            />
            <el-button type="primary" text @click="onClickMapPosition">
              地图定位
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">不再合作</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 高德地图定位 -->
    <el-dialog
      title="地图定位"
      v-model="isMapShow"
      width="850px"
      append-to-body
    >
      <mapPosition :position="positionData" @get-position="getPosition" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="isMapShow = false">确 定</el-button>
          <el-button @click="isMapShow = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="CustomerInfo">
import { ref } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  getClientApi,
  deleteClientApi,
  addClientApi,
  getClientByIdApi,
  putClientApi,
} from "@/api/customerManagement/index";
import mapPosition from "../signIn/mapPosition.vue";

const { proxy } = getCurrentInstance();
const dataSource = ref([]);
const loading = ref(true);
const open = ref(false);
const title = ref("");
const total = ref(0);
const isMapShow = ref(false);
const data = reactive({
  form: {
    name: "",
    avatar: "",
    phone: "",
    position: "", //客户职位
    address: "", //客户地址
    addressDetail: "", //详细地址
    status: 1, //状态 0：不再合作 1：正常
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
    phone: [
      { required: false, message: "手机号码不能为空", trigger: "blur" },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    addressDetail: [
      { required: true, message: "请输入经纬度", trigger: "blur" },
      {
        pattern:
          /^[\-\+]?(0?\d{1,2}\.\d{1,6}|1[0-7]?\d{1}\.\d{1,6}|180\.0{1,6}),[\-\+]?([0-8]?\d{1}\.\d{1,6}|90\.0{1,6})/,
        message: "经纬度格式不正确，正确格式为：104.061382,30.569197",
        trigger: "blur",
      },
    ],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
  },
});

const { form, rules, queryParams } = toRefs(data);

/** 查询客户信息列表 */
function getList() {
  loading.value = true;
  getClientApi(queryParams.value).then((response) => {
    dataSource.value = response.rows;
    total.value = Number(response.total);
    loading.value = false;
  });
}

/**
 * 按客户名称查找客户
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增客户信息";
}

/**
 * 将已有的经纬度值传给地图组件
 */
const positionData = ref([104.063403, 30.568744]);
const onClickMapPosition = () => {
  if (form.value.id) {
    positionData.value = form.value.addressDetail.split(",");
  }
  isMapShow.value = true;
};

/**
 * 获取新的经纬度值
 * @param val
 */
const getPosition = (val) => {
  form.value.addressDetail = `${val.lng},${val.lat}`;
};

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const postId = row.id;
  getClientByIdApi(postId).then((response) => {
    const data = response.data;
    form.value = {
      id: data.id,
      name: data.name,
      avatar: data.avatar,
      phone: data.phone,
      position: data.position,
      address: data.address,
      addressDetail: data.addressDetail,
      status: data.status,
    };
    open.value = true;
    title.value = "修改客户信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        putClientApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addClientApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 表单重置 */
function reset() {
  form.value = {
    name: "",
    avatar: "",
    phone: "",
    position: "",
    address: "",
    addressDetail: "",
    status: 1,
  };
  proxy.resetForm("postRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.id;
  proxy.$modal
    .confirm('是否确认删除客户名称为"' + row.name + '"的数据项？')
    .then(function () {
      return deleteClientApi(postIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
}

getList();
</script>
<style scoped>
:deep(.el-form-item) {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
